﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Input;
using 学生册成绩管理系统.DAL;
using 学生册成绩管理系统.Models;
using 学生册成绩管理系统.MVVM;
using 学生册成绩管理系统.Views;
using 学生册成绩管理系统.BLL;

namespace 学生册成绩管理系统.ViewModels
{
    public class LoginViewModel
    {
        private Student student = new Student();
        public Student Student
        {
            get { return student; }
            set { student = value; }
        }

        public ICommand LoginCommand { get; }
        public ICommand RegisterCommand { get; }
        public LoginViewModel()
        {
            LoginCommand = new RelayCommand(Login);
            RegisterCommand = new RelayCommand(Register);
        }

        private void Register()
        {
            new RegisterWindow().ShowDialog();
        }

        private void Login(object obj)  // 这里的obj就是前端传过来的LoginWindow
        {
            StudentService studentService = new StudentService();
            List<Student> students = studentService.Login(Student);

            // 因为我执行了where语句，间接查询了这张表中有没有符合的数据
            if (students.Count > 0)
            {
                AppData.Instance.CurrentUser = students[0];
                MessageBox.Show("登录成功");
                MainWindow mainWindow = new MainWindow();
                mainWindow.Show();
                // 目的：关闭LoginWindow
                LoginWindow loginWindow = obj as LoginWindow;
                if (loginWindow != null)
                {
                    loginWindow.Close();
                }
            }
            else
            {
                MessageBox.Show("用户名和密码错误");
            }

            // 原始判断方式
            //if (student.Name == row.ItemArray[1].ToString() && student.Password == row.ItemArray[2].ToString())
            //{
            //    MessageBox.Show("登录成功");
            //    MainWindow mainWindow = new MainWindow();
            //    mainWindow.Show();
            //}
            //else
            //{
            //    MessageBox.Show("登录失败");
            //}
        }
    }
}
